<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class RelationshipCase extends Model
{
    protected $table = 'c_relationship_cases';

    public function addRelation($param)
    {
        $has = $this->getRelateInfo($param);
        if ($has === true) {
            $this->user_id = $param['user_id'];
            $this->case_id = $param['case_id'];
            return $this->save();
        }
        return $has;
    }

    /**
     * @param $data
     * @return bool|string
     * 获取关联信息
     */
    public function getRelateInfo($data)
    {
        $info = (new CaseDescribe())->where([['id', '=', $data['case_id']]])->first();
        if (empty($info)) {
            return "该病例不存在,不能绑定!";
        }
        if ($info->user_id == $data['user_id']) {
            return "自己的病例不能与自己关联!";
        }
        $is_relate = $this->where([['case_id', '=', $data['case_id']]])->first();
        if (!empty($is_relate)) {
            return "该病例已被绑定,不能重复绑定!";
        }
        $has = $this->where([['user_id', '=', $data['user_id']], ['case_id', '=', $data['case_id']]])->first();
        if (!empty($has)) {
            return "您已经绑定该病例,不能重复绑定!";
        }
        return true;
    }

    /***
     *取消关联
     */
    public function cancleRelation($data)
    {
        $info = (new CaseDescribe())->where([['id', '=', $data['case_id']]])->first();
        if (empty($info)) {
            return "该病例不存在,不能绑定!";
        }
        if ($info->user_id != $data['user_id']) {
            return "该病例您无权取消关联!";
        }
        $is_relate = $this->where([['case_id', '=', $data['case_id']]])->first();
        if (empty($is_relate)) {
            (new CaseDescribe())->where([['id', '=', $data['case_id']]])->delete();
            return true;
        }
        $this->where([['case_id', '=', $data['case_id']]])->delete();
        return true;
    }
}
